// src/router/index.js
import { createRouter, createWebHistory } from 'vue-router';
import { ElMessage } from 'element-plus';

import UserProfile from '../views/user/UserProfile.vue';
import MachineAdd from '../views/machine/MachineAdd.vue';
import MachineInfo from '../views/machine/MachineInfo.vue';
import MachineDetail from '../views/machine/MachineDetail.vue';
import statsOverview from '../views/stats/MachineOverview.vue';
import statsDetail from '../views/stats/MachineDetail.vue';
import statsPredict from '../views/stats/MachinePredict.vue';

const routes = [
  { path: '/user/profile', name: 'UserProfile', component: UserProfile, },
  { path: '/machine/add',  name: 'MachineAdd', component: MachineAdd, },
  { path: '/machine/info',  name: 'MachineInfo', component: MachineInfo, },
  { path: '/machine/detail/:id',  name: 'MachineDetail', component: MachineDetail, },
  { path: '/stats/overview', name: 'statsOverview', component: statsOverview, },
  { path: '/stats/detail', name: 'statsDetail', component: statsDetail, },
  { path: '/stats/predict', name: 'statsPredict', component: statsPredict, },
];

const router = createRouter({
  history: createWebHistory(),
  routes
});

router.beforeEach(async (to, from, next) => {
  const { useUserStore } = await import('@/stores/user');
  const { usePermissionStore } = await import('@/stores/permission');

  const userStore = useUserStore();
  const permissionStore = usePermissionStore();

  const userRole = userStore.user?.role;
  const restrictedPaths = permissionStore.getForbiddenPaths(userRole || '');

  if (!userRole) {
    next(false);
    return;
  }

  if (!restrictedPaths) {
    ElMessage.error('权限信息丢失，请刷新网页');
    next(false);
    return;
  }

  // 检查即将导航到的路径是否在受限路径中
  if (restrictedPaths.some(path => to.path.startsWith(path))) {
    ElMessage.error('权限不足，无法访问该页面');
    next(false); // 阻止导航
    return;
  }

  next(); // 允许导航
});

export default router;